/****

    activequant - activestocks.eu

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

	
	contact  : contact@activestocks.eu
    homepage : http://www.activestocks.eu

****/
package org.activequant.dao.hibernate;

import java.text.MessageFormat;
import java.util.List;

import org.activequant.core.domainmodel.InstrumentSpecification;
import org.activequant.core.domainmodel.account.Order;
import org.activequant.core.domainmodel.account.Position;
import org.activequant.core.domainmodel.data.Candle;
import org.activequant.core.domainmodel.data.Quote;
import org.activequant.core.domainmodel.data.TradeIndication;
import org.activequant.core.domainmodel.marketscanner.MarketScan;
import org.activequant.core.domainmodel.marketscanner.ScanCriteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * Holds all HQL queries which is easier to maintain.<br>
 * <br>
 * <b>History:</b><br>
 *  - [25.09.2007] Created (Erik Nijkamp)<br>
 *  - [29.09.2007] Added deleteContractEntities() (Erik Nijkamp)<br>
 *
 *  @author Erik Nijkamp
 */
public class HqlQueries {
	
	// hql
	/**
	 * private static final String UPDATE_ELEMENT_SPEC_ID = "update {0} set instrumentspecification = {1} where id = {2}";
	 */
	private static final String UPDATE_ELEMENT_SPEC_ID = "update {0} set instrumentspecification = {1} where id = {2}";
	/**
	 * private static final String DELETE_SPEC_ENTITIES = "delete {0} where instrumentspecification = {1}";
	 */
	private static final String DELETE_SPEC_ENTITIES = "delete {0} where instrumentspecification = {1}";
	/**
	 * private static final String DELETE_SCAN_CRITERIA_ENTITIES = "delete {0} where scanCriteria = {1}";
	 */
	private static final String DELETE_SCAN_CRITERIA_ENTITIES = "delete {0} where scanCriteria = {1}";
	
	// parameters
	/**
	 * private static final Class<?>[] SPEC_ENTITIES = {Candle.class, Quote.class, TradeIndication.class, Order.class, Position.class};
	 */
	private static final Class<?>[] SPEC_ENTITIES = {Candle.class, Quote.class, TradeIndication.class, Order.class, Position.class};
	/**
	 * private static final Class<?>[] SCAN_CRITERIA_ENTITIES = {MarketScan.class};
	 */
	private static final Class<?>[] SCAN_CRITERIA_ENTITIES = {MarketScan.class};
	/**
	 * Updates/saves the given persistent element(T) and sets its instrumentspecification with the given contractId(long).<br/>
	 * It executes a query in the form:<br/>
	 * <strong>persist the given element(T) (insert or update)</strong><br/>
	 * <strong>update ${element.class.name} set instrumentspecification = ${contractId} where id = {2}</strong>
	 * @param <T>
	 * @param ht
	 * @param element
	 * @param contractId
	 */
	@SuppressWarnings("unchecked")
	public static <T> void saveElementWithSeriesId(HibernateTemplate ht, T element, long contractId) {
		long elementId = (Long) ht.save(element);
		String hql = fill(UPDATE_ELEMENT_SPEC_ID, element.getClass().getName(), contractId, elementId);
		ht.bulkUpdate(hql);
	}
	
	/**
	 * Deletes all persistent instances of the {Candle.class, Quote.class, TradeIndication.class, Order.class, Position.class} whose 
	 * instrumentspecification matches one of the given specs(InstrumentSpecification...)<br/>
	 * It executes queries like:<br/>
	 * <strong>delete Candle where instrumentspecification = ?</strong><br/>
	 * <strong>delete Quote where instrumentspecification = ?</strong><br/>
	 * <strong>delete TradeIndication where instrumentspecification = ?</strong><br/>
	 * <strong>delete Order where instrumentspecification = ?</strong><br/>
	 * <strong>delete Position where instrumentspecification = ?</strong>
	 * @param ht
	 * @param specs
	 */
	public static void deleteSpecificationEntities(HibernateTemplate ht, InstrumentSpecification... specs) {
		// related entities
		for(InstrumentSpecification spec : specs) {
			long specId = spec.getId();
			for(Class<?> entity : SPEC_ENTITIES) {			
				// spec -> entity
				String hql = fill(DELETE_SPEC_ENTITIES, entity.getName(), specId);
				ht.bulkUpdate(hql);
			}
		}
	}
	/**
	 * returns the given sql(String) after filling its placeholders with the given args(Object...).<br/>
	 * The given sql(String) should have placeholders, for example: "delete {0} where instrumentspecification = {1}"
	 * @param sql
	 * @param args
	 * @return
	 */
	private static String fill(String sql, Object... args) {
		// convert to strings in order to avoid formating issues
		Object[] strings = new String[args.length];
		for(int i = 0; i < strings.length; i++) {
			strings[i] = args[i].toString();
		}
		return MessageFormat.format(sql, strings);
	}
	/**
	 * Not HQL query but does cascade delete and I need that here
	 * Deletes all persisted MarketScan's (and their MArketScanRows) whose ScanCriteria matches one of the given specs(ScanCriteria...)
	 * @param ht
	 * @param specs
	 */
	public static void deleteScanCriteriaEntities(HibernateTemplate ht, ScanCriteria... specs) {
		// related entities
		for(ScanCriteria spec : specs) {
			//long specId = spec.getId();
			//for(Class<?> entity : SCAN_CRITERIA_ENTITIES) {	
				DetachedCriteria criteria = DetachedCriteria.forClass(MarketScan.class).add(Expression.eq("scanCriteria", spec));
				
				List<MarketScan> list = ht.findByCriteria(criteria);	
				ht.deleteAll(list);
				//String marketScanRowshql = fill("delete {0} msr where msr.parent is not null and msr.parent.id={1}.id and {1}.scanCriteria = {2}", MarketScanRow.class.getName(),MarketScan.class.getName(), specId);
				//ht.bulkUpdate(marketScanRowshql);
				// spec -> entity
				//String hql = fill(DELETE_SCAN_CRITERIA_ENTITIES, entity.getName(), specId);
				//ht.bulkUpdate(hql);
			//}
		}
	}

}
